<?php
/**
 * Created by PhpStorm.
 * User: yangjiaming
 * Date: 2018/2/5
 * Time: 12:35
 */

namespace Halo\Validator;

use Halo\Validator\ParamRule;
class ParamValidator
{
    static function getPairParam(ParamRule &$rule, $item = [])
    {

    }
    static function getParam(&$request, ParamRule &$rule)
    {
        //$param = $request->get($rule->name, $rule->defaultValue);
    }
    static function paramsFromRequestAndRules(Request $request, array $rules, array $validate = [])
    {
        $params = $request->param('', '');
        $param = [];
        foreach ($rules as $key => $val) {
            if($val == true && empty($params[$key])) {
                throw new \Exception(ParamValidator::requiredErrorDesc($key), -100);
            }
            if(isset($validate[$key]) && $params[$key]) {
                if(!ParamRule::validate($params[$key], $validate[$key])) {
                    throw new \Exception(ParamValidator::wrongFormatErrorDesc($key), -100);
                }
            }
            $param[$key] = $params[$key];
        }
        $param = array_filter($param);
        return $param;
    }
    static function requiredErrorDesc($title) {
        return sprintf('%s 是必填参数', $title);
    }

    static function valueErrorDesc($title) {
        return sprintf('%s 取值非法', $title);
    }

    static function rangeErrorDesc($title, $min, $max) {
        return sprintf('%s 不在可选范围 [%d:%d]', $title, $min, $max);
    }

    static function emptyErrorDesc($title) {
        return sprintf('%s 不能为空', $title);
    }

    static function strLengthErrorDesc($title, $length, $minLength, $maxLength) {
        if ($length < $minLength) {
            return sprintf('%s 最短长度为%d', $title, $minLength);
        }

        return sprintf('%s 最长不超过 %d', $title, $maxLength);
    }

    static function wrongFormatErrorDesc($title) {
        return sprintf('%s 格式不对', $title);
    }
}